package pay

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"goskeleton/app/model"
	"goskeleton/app/utils/response"
	"goskeleton/app/utils/xunhupay"
	"strconv"
)

// 虎皮椒微信支付接口
type PayController struct {
}

func (w *PayController) Pay(c *gin.Context) {

	appId := "201906162624"                               //Appid
	appSecret := "9c184ffa9d69f42e3e5e8010c23b7f0e"       //密钥
	var host = "https://api.xunhupay.com/payment/do.html" //跳转支付页接口URL
	client := xunhupay.NewHuPi(&appId, &appSecret)        //初始化调用

	var order model.Order
	if err := c.ShouldBind(&order); err != nil {
		// 处理错误
	}
	//根据订单号查询出价格来
	amount := model.CreateOrderFactory("mysql").GetOrderAmountByTradeId(order.TradeId)

	//支付参数，appid、time、nonce_str和hash这四个参数不用传，调用的时候执行方法内部已经处理
	notify_url := "http://sxl-setvice.natapp1.cc/admin/second_hand/notifyResult?tradeId=" + order.TradeId + "&product_id=" + strconv.Itoa(order.ProductId) + "&buyer_open_id=" + order.BuyerOpenId
	params := map[string]string{
		"version":        "1.1",
		"trade_order_id": order.TradeId,
		"total_fee":      amount,
		"title":          "商品购买",
		"notify_url":     notify_url,
		"return_url":     "",
		"wap_name":       "sxl店铺",
		"callback_url":   "",
	}
	execute, err := client.Execute(host, params) //执行支付操作
	if err != nil {
		panic(err)
	}
	fmt.Println(execute) //打印支付结果
	//返回url
	response.Success(c, "支付回调", execute)

}

func (w *PayController) NotifyResult(c *gin.Context) {
	//回调，处理成功的结果
	//获取交易单号和商品id
	tradeId := c.Query("tradeId")
	buyerOpenId := c.Query("buyer_open_id")

	//对商品订单进行处理
	model.CreateOrderFactory("mysql").PaySuccess(tradeId, buyerOpenId)

	response.Success(c, "支付成功", nil)
}

//轮询查询订单状态，判断是否支付成功

type QueryResult struct {
	Data struct {
		TransactionID string `json:"transaction_id"`
	} `json:"data"`
}

// Query 查询示例
func (PayController) QueryPayStatus(c *gin.Context) {

	appId := "201906162624"                                  //Appid
	appSecret := "9c184ffa9d69f42e3e5e8010c23b7f0e"          //密钥
	var host = "https://api.xunhupay.com/payment/query.html" //查询接口URL

	tradeId := c.Query("trade_id")

	client := xunhupay.NewHuPi(&appId, &appSecret) //初始化调用

	//查询参数，appid、time、nonce_str和hash这四个参数不用传，调用的时候执行方法内部已经处理
	params := map[string]string{
		"out_trade_order": tradeId,
		//"open_order_id":   "123456789",
	}

	execute, err := client.Execute(host, params) //执行查询操作
	//获取微信单号
	var result QueryResult
	if err := json.Unmarshal([]byte(execute), &result); err != nil {
		panic(err)
	}
	// 获取 transaction_id
	fmt.Println("Transaction ID:", result.Data.TransactionID)
	if result.Data.TransactionID != "" {
		//如果不为空则根据tradeId存储对应的单号TransactionID
		model.CreateOrderFactory("mysql").UpdateTransactionId(tradeId, result.Data.TransactionID)

	}
	if err != nil {
		panic(err)
	}
	//
	fmt.Println(execute) //打印查询结果

	response.Success(c, "查询成功", execute)
}
